package com.qsmx.qingqiuticket.app;

import static androidx.core.content.ContextCompat.registerReceiver;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.core.content.ContextCompat;

import com.qsmx.core.activities.ProxyActivity;
import com.qsmx.core.app.Atmos;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.util.dimen.DimenUtil;
import com.qsmx.qingqiuticket.app.delegate.IndexDelegate;
import com.qsmx.qingqiuticket.app.event.QrScanEvent;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionTag;
import com.qsmx.qingqiuticket.app.util.ByteArrayUtils;
import com.qsmx.qingqiuticket.app.util.Density;
import com.qsmx.qingqiuticket.app.util.HIDKeyConverter;
import com.qsmx.qingqiuticket.app.util.SoundPlayUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import permissions.dispatcher.RuntimePermissions;
import qiu.niorgai.StatusBarCompat;

public class MainActivity extends ProxyActivity {
    private static final String ACTION_USB_PERMISSION = "com.your.package.USB_PERMISSION";
    private final StringBuilder sb = new StringBuilder();
    private UsbManager usbManager;
    private UsbDevice targetUsb;

    private int maxPackageSize;

    private UsbInterface uif;

    private UsbDeviceConnection usbDeviceConnection;

    @Override
    public AtmosDelegate setRootDelegate() {
        return new IndexDelegate();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        Atmos.getConfigurator().withActivity(this);
        StatusBarCompat.translucentStatusBar(this, true);
        Density.setDensity(getApplication(), this);
        SoundPlayUtils.init(this);

        System.out.println("getScreenHeight=========>" + DimenUtil.getScreenHeight());
        System.out.println("getScreenWidth=========>" + DimenUtil.getScreenWidth());

        SoundPlayUtils.init(getApplicationContext());
//        //初始化组件化基础库, 所有友盟业务SDK都必须调用此初始化接口。
//        UMConfigure.init(this, FusionCode.UM_APPKEY, "Umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
//        /**
//         *设置组件化的Log开关
//         *参数: boolean 默认为false，如需查看LOG设置为true
//         */
//        UMConfigure.setLogEnabled(false);

        initQrScanner();
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    private void initQrScanner() {
        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        //目标设备的PID/VID
        int tPid = 0xD101, tVid = 0x26F1;
        targetUsb = null;
        //获得所有USB设备
        HashMap<String, UsbDevice> usbDeviceMap = usbManager.getDeviceList();
        for (final UsbDevice device : usbDeviceMap.values()) {
            if (device.getProductId() == tPid && device.getVendorId() == tVid) {
                //找到USB设备
                targetUsb = device;
                break;
            }
        }

        PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0,
                new Intent(ACTION_USB_PERMISSION),
                Build.VERSION.SDK_INT >= 34 ? PendingIntent.FLAG_IMMUTABLE : PendingIntent.FLAG_MUTABLE);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);//USB插入
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);//USB拔出
        registerReceiver( usbPermissionReceiver, filter);

        if (usbManager.hasPermission(targetUsb)) {
            if (connectUsb()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        StringBuilder sb = new StringBuilder();
                        byte[] buffer = new byte[maxPackageSize];
                        UsbEndpoint inEndpoint = uif.getEndpoint(0);
                        while (!Thread.interrupted()) {
                            int ret = usbDeviceConnection.bulkTransfer(inEndpoint, buffer, buffer.length, 100);
                            if (ret > 0) {
                                byte[] reab = new byte[ret];
                                System.arraycopy(buffer, 0, reab, 0, ret);
                                //Log.d(tag, "读取到数据字节：" + ByteTools.bytesToHexString(reab));

                                if (ByteArrayUtils.contains0x28(reab)) {
                                    if (FusionCode.SCAN_TYPE.equals(FusionCode.QR_SCANNER)) {
                                        if (!FusionCode.QrIsLoading) {
                                            FusionCode.QrIsLoading = true;
                                            Bundle bundle = new Bundle();
                                            bundle.putString(FusionTag.QR_CODE, sb.toString().replace(",", "").replace(" ", ""));
                                            EventBus.getDefault().removeAllStickyEvents();
                                            EventBus.getDefault().postSticky(new QrScanEvent(bundle));
                                        }
                                    }
                                    System.out.println("onUsbHIDScanSuccess=========>" + sb.toString().replace(",", "").replace(" ", ""));
                                    sb = new StringBuilder();
                                } else {
                                    sb.append(HIDKeyConverter.convertToString(reab));
                                }
                            }
                        }

                    }
                }).start();
            }
        } else {
            //请求USB设备权限
            usbManager.requestPermission(targetUsb, mPermissionIntent);
        }
    }

    public boolean connectUsb() {
        //获得USB连接
        usbDeviceConnection = usbManager.openDevice(targetUsb);
        if (targetUsb.getInterfaceCount() == 0) {
            return false;
        }

        uif = targetUsb.getInterface(0);
        int endCount = uif.getEndpointCount();
        if (endCount == 0) {
            return false;
        }
        //获得包数据大小
        maxPackageSize = (uif.getEndpoint(0)).getMaxPacketSize();
        //打开USB设备
        if (!usbDeviceConnection.claimInterface(uif, true)) {
            return false;
        }
        return true;
    }

    private final BroadcastReceiver usbPermissionReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_USB_PERMISSION.equals(intent.getAction())) {
                UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if (device != null) {
                        // Permission granted, proceed with USB operations
                        if (connectUsb()) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    StringBuilder sb = new StringBuilder();
                                    byte[] buffer = new byte[maxPackageSize];
                                    UsbEndpoint inEndpoint = uif.getEndpoint(0);
                                    while (!Thread.interrupted()) {
                                        int ret = usbDeviceConnection.bulkTransfer(inEndpoint, buffer, buffer.length, 100);
                                        if (ret > 0) {
                                            byte[] reab = new byte[ret];
                                            System.arraycopy(buffer, 0, reab, 0, ret);
                                            //Log.d(tag, "读取到数据字节：" + ByteTools.bytesToHexString(reab));

                                            if (ByteArrayUtils.contains0x28(reab)) {
                                                if (FusionCode.SCAN_TYPE.equals(FusionCode.QR_SCANNER)) {
                                                    if (!FusionCode.QrIsLoading) {
                                                        FusionCode.QrIsLoading = true;
                                                        Bundle bundle = new Bundle();
                                                        bundle.putString(FusionTag.QR_CODE, sb.toString().replace(",", "").replace(" ", ""));
                                                        EventBus.getDefault().removeAllStickyEvents();
                                                        EventBus.getDefault().postSticky(new QrScanEvent(bundle));
                                                    }
                                                }
                                                System.out.println("onUsbHIDScanSuccess=========>" + sb.toString().replace(",", "").replace(" ", ""));
                                                sb = new StringBuilder();
                                            } else {
                                                sb.append(HIDKeyConverter.convertToString(reab));
                                            }
                                        }
                                    }

                                }
                            }).start();
                        }
                    }
                } else {
                }
            }
        }
    };

}